package com.la100.common.utils;

import okhttp3.*;

import java.io.IOException;

public class OkHttpUtil {

	public static final MediaType JSON = MediaType
			.parse("application/json; charset=utf-8");

	/**
	 * 同步请求
	 * 
	 * @param url
	 * @return
	 */
	public static String getSync(String url) {
		// url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";
		String responseData = "";
		OkHttpClient mHttpClient = new OkHttpClient();

		Request request = new Request.Builder().url(url).build();
		Response response = null;
		try {
			response = mHttpClient.newCall(request).execute();
			responseData = response.body().string();
			//LogUtils.debug(responseData);

		} catch (IOException e1) {
			e1.printStackTrace();
		}

		return responseData;
	}

	/**
	 * post 同步请求
	 * 
	 * @param url
	 * @param json
	 *            请求的json数据
	 * @return
	 */
	public static String postSync(String url, String json) {
		OkHttpClient client = new OkHttpClient();
		RequestBody body = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(body).build();
		Response response = null;
		try {
			response = client.newCall(request).execute();
			return response.body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getAsync(String url) {
		// url = "http://write.blog.csdn.net/postlist/0/0/enabled/1";
		String responseData = "";
		OkHttpClient mHttpClient = new OkHttpClient();

		Request request = new Request.Builder().url(url).build();
		mHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {

			}

			@Override
			public void onResponse(Call call, Response response)
					throws IOException {
				String json = response.body().string();
				LogUtils.debug(json);
			}
		});

		return responseData;
	}

	public static void main(String[] args) {
		OkHttpUtil.getSync("");
	}
}
